/**
 * Copyright (c) 2018, 西安星沙网络科技-版权所有
 *
 * Licensed under the GNU Lesser General Public License (LGPL) ,Version 3.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.gnu.org/licenses/lgpl-3.0.txt
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.waleychain.exchange.dfs.provider;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import cn.waleychain.exchange.core.constant.DDIC;
import cn.waleychain.exchange.core.entity.PageInfo;
import cn.waleychain.exchange.core.logger.LoggerHelper;
import cn.waleychain.exchange.core.result.DefaultResult;
import cn.waleychain.exchange.core.result.IBaseResult;
import cn.waleychain.exchange.dfs.bean.FastdfsUploadResult;
import cn.waleychain.exchange.dfs.core.FastdfsApplication;
import cn.waleychain.exchange.dfs.core.FastdfsException;
import cn.waleychain.exchange.model.FileResource;
import cn.waleychain.exchange.service.dfs.ResourceService;

@RestController
@RequestMapping("/dfs")
public class DfsServiceProvider {

	private static final Logger mLog = LoggerFactory.getLogger(DfsServiceProvider.class);
	
	@Autowired
	private ResourceService resourceService;
	
	/**
	 * 获取文件资源列表
	 * @param name
	 * @param type
	 * @param showCount
	 * @param currentPage
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value = "/fetchResourcesList")
	public PageInfo<FileResource> fetchResourcesList(@RequestParam(required = false) String name, 
			@RequestParam(required = false) Integer type, 
			@RequestParam int showCount, @RequestParam int currentPage) throws Exception {
		
		return resourceService.fetchResourcesList(name, type, showCount, currentPage);
	}
	
	@RequestMapping(value = "/upload", produces = "text/plain;charset=UTF-8")
	public @ResponseBody IBaseResult upload(HttpServletRequest req) {
		// Create a factory for disk-based file items
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// Get upload size.
		int uploadSize = FastdfsApplication.application.getGlobalConfiguration().getDFSUploadSizePer();
		// Get upload number.
		int uploadNumber = FastdfsApplication.application.getGlobalConfiguration().getDFSUploadNumberPer();

		// Set factory constraints
		factory.setSizeThreshold(4096);
		// factory.setRepository(new

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);

		try {
			// Set overall request size constraint
			// upload.setSizeMax(uploadSize);

			List<FileItem> items = upload.parseRequest(req);
			if (items.size() > uploadNumber) {
				throw new FastdfsException("Upload file number out of the limit, max upload number: " + uploadNumber);
			}

			Iterator<FileItem> i = items.iterator();
			List<FastdfsUploadResult> rsList = new ArrayList<FastdfsUploadResult>();

			while (i.hasNext()) {
				FileItem fi = (FileItem) i.next();
				if (fi != null) {
					FastdfsUploadResult rs = null;

					if (rs == null) {
						try {
							if (fi.getSize() > uploadSize) {
								rs = new FastdfsUploadResult(
										fi.getName() + " size out of the limit, max upload size: " + uploadSize);
							} else {
								rs = FastdfsApplication.application.upload(fi.getInputStream(), fi.getSize(),
										fi.getName());
							}
						} catch (Exception e) {
							e.printStackTrace();

							rs = new FastdfsUploadResult(fi.getName() + " upload failed, caused by: " + e.getMessage());
						}
					}
					rsList.add(rs);
				}
			}
			
			List<FileResource> batchInsertList = new ArrayList<>(rsList.size());
			for (FastdfsUploadResult result : rsList) {
				if (FastdfsUploadResult.STATUS_SUCCESS == result.getStatus()) {
					FileResource fr = new FileResource();
					fr.setType(DDIC.ResourceType.IMAGE.id);
					fr.setName(result.getRemoteFileName());
					fr.setDescription(result.getOriginalName());
					fr.setUrl(result.getUrl());
					fr.setCreateTime(new Date());
					fr.setModifiedTime(new Date());
					
					batchInsertList.add(fr);
					fr = null;
				}
			}
			
			if (batchInsertList.size() > 0) {
				resourceService.batchInsert(batchInsertList);
			}

			return DefaultResult.buildSuccessResult(rsList);
			
		} catch (Exception e) {
			LoggerHelper.printLogErrorNotThrows(mLog, e, "文件上传");
		}
		
		return DefaultResult.buildFailedResult();
	}
}
